<template>
  <!-- ai问课手机端页面 -->
  <div class="code-content w-100 bg-fff">
    <!-- <div class="header-container"> -->
    <!-- 顶部状态栏占位 -->
    <!-- <div class="status-bar"></div> -->
    <!-- 自定义导航栏 -->
    <!-- <div class="custom-header">
        <div class="back-btn icon-size-24" @click="goBack"></div>
        <div class="title">
          <span>《{{ dynamicTitle }}》</span>
          <span class="titleStatus color-00065 text-center">已结束</span>
        </div>
      </div>
    </div> -->
    <div class="content">
      <div
        class="code-top display-flex flex-between align-items-center text-center color-fff"
      >
        <div>
          <span class="font-size-16 font-weight-500"
            >第{{ detailData?.xueshi }}学时</span
          >
        </div>
        <div class="font-size-14">
          <span
            class="pptVideo margin-right-8 cursor-pointer"
            v-for="(item, index) in videoTextList"
            :key="index"
            :class="textIndex == index ? 'active' : ''"
            @click="handleVideo(index)"
            >{{ item.text }}</span
          >
        </div>
      </div>
      <div class="video-content">
        <video
          class="w-100 h-100"
          autoplay
          controls
          ref="pptVideoRef"
          playsinline
          @timeupdate="handleTimeUpdate"
        ></video>
      </div>
      <div class="course-title">
        <div class="course-markers color-fff text-center"></div>
        <div class="title-item margin-right-16">
          <img
            class="icon-size-16 mr-3"
            src="@/assets/images/classroom.png"
            alt=""
          />
          <span class="font-size-14 vertical-align-middle">{{
            detailData?.classRoomName
          }}</span>
        </div>
        <div class="margin-right-16 title-item">
          <img
            class="icon-size-16 mr-3"
            src="@/assets/images/teacher.png"
            alt=""
          />
          <span class="font-size-14 vertical-align-middle">{{
            detailData?.ghNames
          }}</span>
        </div>
        <div class="margin-right-16 title-item">
          <img
            class="icon-size-16 mr-3"
            src="@/assets/images/class.png"
            alt=""
          />
          <span class="font-size-14 vertical-align-middle">{{
            detailData?.bh
          }}</span>
        </div>
      </div>
      <!-- ppt区域 -->
      <div class="pptBox w-100" ref="pptRef">
        <div
          :ref="
            (el) => {
              if (el) pptItems[index] = el
            }
          "
          class="pptItem"
          :class="getActiveClass(index)"
          @click="handlePpt(item.timestamp, index)"
          v-for="(item, index) in pptList"
          :key="index"
        >
          <img class="w-100 h-100" :src="item.url" alt="" />
          <div class="pptNum color-fff font-size-14">{{ index + 1 }}</div>
          <div class="pptTime color-fff font-size-14">
            {{ convertTimes(item.timestamp) }}
          </div>
        </div>
      </div>
      <div class="rim w-100"></div>
      <!-- ai提问 -->
      <div class="aiBox bg-fff">
        <!-- <p class="font-size-18 font-weight-500 aiTitle">AI提问</p> -->
        <div class="aiProblem">
          <!-- <div class="aiProblem-item font-size-14 font-weight-500">
          生物化学D的相关课程
        </div>
        <div class="aiProblem-item font-size-14 font-weight-500">
          如何通过物联网设备与区块链技术实现农产品质量溯源？
        </div> -->
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import Hls from 'hls.js'
import { getRecordVideoList } from '@/services/recordedBroadcast'
import {
  getVideoList,
  getcourseDetail,
  getCoursePlay,
  getPpt
} from '@/services/liveBroadcast'
import { convertTimes, timeToSeconds } from '@/utils/crypto'
import { useUserStore } from '@/stores/modules/user'
const userStore = useUserStore()
const route = useRoute()
const courseId = ref()
const detailData = ref()
const pptList = ref()
// 课程直播状态
const playStatus = ref()
// ppt视频地址（主画面路径）
const pptVideoRef = ref<HTMLMediaElement | null | any>(null)
const pptUrls = ref({
  hdUrl: '' // 高清画质
})
const afterUrls = ref({
  // 后置摄像头
  hdUrl: '' // 高清画质
})
const centerUrls = ref({
  hdUrl: '' // 中间播放的url
})
const videoTextList = ref([
  {
    index: 0,
    text: '线路1'
  },
  {
    index: 1,
    text: '线路2'
  }
])
const textIndex = ref(0)
const centerVideoCurrentTime = ref()
const dynamicTitle = ref()
const pptItems: any = ref<(HTMLDivElement | null)[]>([])
const pptVideoTime = ref(0) // 录播ppt时时播放时间
const selectPpt: any = ref() // 选中的ppt
const pptRef = ref<HTMLDivElement | null>(null) // ppt-content 容器引用

onMounted(async () => {
  courseId.value = route.query.id
  handlecourseDetail(courseId.value)
  if (route.query.videoTime) {
    centerVideoCurrentTime.value = timeToSeconds(route.query.videoTime)
  }
})

// 切换视频
const handleVideo = (index: any) => {
  textIndex.value = index
  if (index == 0) {
    // ppt画面
    centerUrls.value.hdUrl = pptUrls.value.hdUrl
  } else {
    // 后置摄像头画面
    centerUrls.value.hdUrl = afterUrls.value.hdUrl
  }
  switchVideo()
}

// 通过课程id获取详情
const handlecourseDetail = async (val: any) => {
  if (val) {
    const courseDetailRes = await getcourseDetail(val)
    if (courseDetailRes.code == 200) {
      detailData.value = courseDetailRes?.data
      document.title = detailData.value.kcmc
      // dynamicTitle.value = detailData.value.kcmc
      // 获取课程直播状态
      getPlayStatus()
    }
  }
}

// 获取视频播放状态
const getPlayStatus = async () => {
  const classRoomNo = detailData.value.classRoomNo
  const date = detailData.value.viewDate
  const classSeq = detailData.value.classSeq
  const statusRes: any = await getCoursePlay(classRoomNo, date, classSeq)
  if (statusRes.code == 200) {
    const statusTitle = statusRes.data
    if (statusTitle == 'DONE' || statusTitle == 'EDITING') {
      // 直播已结束
      playStatus.value = 0 // 0已结束 1正在直播中
      // 获取录播视频流
      recoredVideoUrls()
    } else {
      playStatus.value = 1
      // 获取直播视频流
      handleVideoUrls()
    }
    // 获取ppt
    getPptList()
  }
}

// 获取直播视频流
const handleVideoUrls = async () => {
  // 获取直播视频
  const RoomNo = detailData.value.classRoomNo
  const userName = userStore.userInfo?.userName
  const videoUrlsRes: any = await getVideoList(RoomNo, userName)
  if (videoUrlsRes && videoUrlsRes.code == 200) {
    if (videoUrlsRes.data.length > 0) {
      handleUrls(videoUrlsRes)
    }
  }
  switchVideo()
}

// 获取视频播放
const switchVideo = () => {
  // 播放视频
  const pptHls = new Hls()
  if (Hls.isSupported()) {
    pptHls.loadSource(centerUrls.value.hdUrl)
    pptHls.attachMedia(pptVideoRef.value!)
    // 录播恢复播放时间
    if (playStatus.value == 0 && centerVideoCurrentTime.value > 0) {
      pptVideoRef.value.currentTime = centerVideoCurrentTime.value
    }
  } else {
    console.error('HLS is not supported')
  }
}

// 获取录播视频流
const recoredVideoUrls = async () => {
  const classRoomNo = detailData.value.classRoomNo
  const viewDate = detailData.value.viewDate
  const classSeq = detailData.value.classSeq
  const userName = userStore.userInfo?.userName
  const videoUrlsRes: any = await getRecordVideoList(
    classRoomNo,
    viewDate,
    classSeq,
    userName
  )
  if (videoUrlsRes && videoUrlsRes.code == 200) {
    if (videoUrlsRes.data.length > 0) {
      handleUrls(videoUrlsRes)
    }
  }
  switchVideo()
}

// 直/录播视频流返回数据处理
const handleUrls = (videoUrlsRes: any) => {
  videoUrlsRes.data.forEach((item: any) => {
    // ppt画面
    if (item.channel == 1) {
      item.urlList.forEach((urlItem: any) => {
        if (urlItem.definition == 'default') {
          // ppt高清画面
          pptUrls.value.hdUrl = urlItem.url
          centerUrls.value.hdUrl = urlItem.url
        }
      })
    }
    // 后置摄像头画面
    if (item.channel == 2) {
      item.urlList.forEach((urlItem: any) => {
        if (urlItem.definition == 'default') {
          //高清画面
          afterUrls.value.hdUrl = urlItem.url
        }
      })
    }
  })
}

const getPptList = async () => {
  try {
    const classRoomNo = detailData.value.classRoomNo
    const date = detailData.value.viewDate
    const classSeq = detailData.value.classSeq
    // 获取PPT列表数据
    const pptRes = await getPpt(classRoomNo, date, classSeq)
    pptList.value = pptRes?.data || []
  } catch (error) {
    console.error('获取PPT列表失败:', error)
  }
}

// const goBack = () => {
//   history.back()
// }

// 点击ppt跳到指定时间
const handlePpt = (time: any, index: any) => {
  // 视频跳转到ppt生成的指定时间
  const pptVideo = pptVideoRef.value
  if (pptVideo) {
    pptVideo.currentTime = time / 1000000 // 设置视频的当前时间
    pptVideo.play() // 自动播放视频
  }
  scrollToActiveItem(1)
}

// 录播视频播放时间
const handleTimeUpdate = async () => {
  pptVideoTime.value = Math.trunc(pptVideoRef.value.currentTime)
}

// 计算属性：找到 pptVideoTime <= item.timestamp 的最近一个索引
const nearestPptIndex = computed(() => {
  if (pptVideoTime.value == null) return -1
  // 从后往前找第一个时间小于等于当前视频时间的PPT
  console.log(pptList.value)
  for (let i = pptList.value?.length - 1; i >= 0; i--) {
    const pptTime = pptList.value[i].timestamp / 1000000 // 假设时间需要转换
    if (pptVideoTime.value >= pptTime) {
      return i
    }
  }
  return 0
})

// 监听视频对应ppt高亮项变化
watch(
  () => nearestPptIndex.value,
  async (newIndex, oldIndex) => {
    // console.log('nearestPptIndex changed:', oldIndex, '->', newIndex)
    if (newIndex !== -1 && newIndex !== oldIndex) {
      try {
        await scrollToActiveItem(0)
      } catch (error) {
        console.error('Scroll failed:', error)
      }
    }
  },
  { flush: 'post' } // 确保在DOM更新后执行
)

// 录播状态滚动到当前高亮项
// 滚动到当前高亮项
const scrollToActiveItem = async (val: any) => {
  // val 0自动播放 1用户点击
  await nextTick() // 等待 DOM 更新
  let activeIndex
  if (val == 0) {
    activeIndex = nearestPptIndex.value
  }
  if (val == 1) {
    activeIndex = selectPpt.value
  }
  if (activeIndex === -1 || !pptItems.value[activeIndex] || !pptRef.value) {
    return
  }
  const item = pptItems.value[activeIndex]
  const container = pptRef.value

  // 计算元素和容器的位置
  const itemLeft = item.offsetLeft
  const itemWidth = item.clientWidth
  const containerWidth = container.clientWidth

  // 计算目标滚动位置，使元素垂直居中
  const targetScrollLeft = itemLeft - containerWidth / 2 + itemWidth / 2

  // 平滑滚动
  container.scrollTo({
    left: targetScrollLeft,
    behavior: 'smooth'
  })
}

// 直播/录播同步找到ppt列表项
// 判断当前项是否应该高亮
const getActiveClass = (index: number) => {
  if (selectPpt.value != null) {
    if (selectPpt.value !== nearestPptIndex.value) {
      return index === nearestPptIndex.value ? 'activePpt' : ''
    } else {
      return selectPpt.value === index ? 'activePpt' : ''
    }
  } else {
    return index === nearestPptIndex.value ? 'activePpt' : ''
  }
}
</script>

<style lang="scss" scoped>
.code-content {
  height: 100vh;
  .code-top {
    height: 40px;
    padding: 0 12px;
    box-sizing: border-box;
    background: linear-gradient(214deg, #666666 0%, #000000 100%);
    span {
      display: inline-block;
    }
    .playStatus {
      width: 41px;
      height: 16px;
      line-height: 16px;
      font-size: 11px;
      margin-left: 6px;
      background: linear-gradient(315deg, #0f63ed 0%, #69a1fe 100%);
      border-radius: 2px 2px 2px 2px;
    }
    .pptVideo {
      padding: 2px 12px;
      box-sizing: border-box;
      border-radius: 4px 4px 4px 4px;
      border: 1px solid #f7f7f7;
    }
    .active {
      background: #0f63ed;
      border-color: #0f63ed;
    }
  }
  .video-content {
    height: 180px;
  }
  .course-title {
    padding: 12px;
    box-sizing: border-box;
    .course-markers {
      width: 84px;
      height: 24px;
      background: url('@/assets/images/courseMarker.png') no-repeat;
      background-size: 100%;
      margin-bottom: 10px;
    }
  }
  .courseDetail {
    padding: 12px;
    box-sizing: border-box;
    .signPeople {
      padding-right: 20px;
      box-sizing: border-box;
      border-right: 1px solid #e8e8e8;
    }
    .workPeople {
      padding-left: 20px;
      box-sizing: border-box;
    }
  }
}
.people-box {
  height: 228px;
  padding: 12px;
  box-sizing: border-box;
  background: #3d3d3d;
  border-radius: 6px 6px 6px 6px;
  .courseData {
    margin-top: 12px;
    height: 136px;
    background: #1b1b1b;
    border-radius: 4px 4px 4px 4px;
    padding: 12px 30px;
    box-sizing: border-box;
    div {
      width: 33.33%;
      float: left;
    }
    p {
      margin-bottom: 9px;
    }
  }
}
.mr-3 {
  margin-right: 3px;
}
.mb-18 {
  margin-bottom: 18px;
}
// ppt
.pptBox {
  padding: 12px;
  box-sizing: border-box;
  overflow-x: auto; /* 自动显示横向滚动条（仅在需要时） */
  white-space: nowrap; /* 防止内容换行 */
  .pptItem {
    width: 128px;
    height: 72px;
    border-radius: 6px;
    margin-right: 12px;
    border: 2px solid #fff;
    display: inline-block; /* 让内容横向排列 */
    position: relative;
    overflow: hidden;
    .pptNum {
      height: 24px;
      line-height: 24px;
      padding: 0px 8px;
      box-sizing: border-box;
      background: rgba(0, 0, 0, 0.6);
      border-radius: 6px 0px 0px 0px;
      position: absolute;
      top: 0px;
      left: 0px;
    }
    .pptTime {
      height: 24px;
      line-height: 24px;
      padding: 0px 8px;
      box-sizing: border-box;
      background: rgba(0, 0, 0, 0.6);
      border-radius: 0px 0px 6px 0px;
      position: absolute;
      bottom: 0px;
      right: 0px;
    }
  }
}
.rim {
  height: 12px;
  background: #f7f7f7;
}
// ai提问
.aiBox {
  padding: 0px 12px 10px;
  box-sizing: border-box;
}
.aiTitle {
  height: 46px;
  line-height: 46px;
}
.aiProblem {
  .aiProblem-item {
    height: 38px;
    line-height: 38px;
    margin-top: 12px;
  }
}
.title-item {
  float: left;
  margin-bottom: 9px;
}
.activePpt {
  border-color: #4c8bf3 !important;
}
/* 适配各种手机状态栏 */
// .content {
//   margin-top: calc(44px + env(safe-area-inset-top));
// }
// .header-container {
//   position: fixed;
//   top: 0;
//   left: 0;
//   width: 100%;
//   z-index: 999;
// }
// .status-bar {
//   height: env(safe-area-inset-top);
//   background: #fff;
// }
// .custom-header {
//   display: flex;
//   align-items: center;
//   height: 44px;
//   background: #fff;
//   box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
//   padding: 0 15px;
// }
// .back-btn {
//   background: url('@/assets/images/arrow-left.png') no-repeat;
//   background-size: 100%;
// }
// .title {
//   flex: 1;
//   text-align: center;
//   font-size: 16px;
//   font-weight: bold;
//   white-space: nowrap;
//   overflow: hidden;
//   text-overflow: ellipsis;
// }
// .content {
//   margin-top: calc(44px + env(safe-area-inset-top));
// }
// .titleStatus {
//   display: inline-block;
//   width: 41px;
//   height: 16px;
//   background: #e8e8e8;
//   border-radius: 2px 2px 2px 2px;
//   font-size: 11px;
// }
</style>
